#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    InitializeUi();

    tcp_socket_ = new QTcpSocket(this);

    status_label_ = new QLabel();
    status_label_->setText("未连接");
    ui->statusbar->addWidget(new QLabel("连接状态:"));
    ui->statusbar->addWidget(status_label_);

    SwitchState(State::kDisconnected);

    InitializeSignalSlot();
}

MainWindow::~MainWindow()
{
    tcp_socket_->close();
    tcp_socket_->deleteLater();
    delete ui;
}

void MainWindow::InitializeUi()
{
    ui->ip_edit->setText("127.0.0.1");
    ui->port_edit->setText("8899");
    setWindowTitle("客户端");
}

void MainWindow::InitializeSignalSlot()
{
    connect(tcp_socket_, &QTcpSocket::connected, this, &MainWindow::ConnectedCallback);

    connect(tcp_socket_, &QTcpSocket::readyRead, this, [=](){
        QByteArray data = tcp_socket_->readAll();
        ui->log_text_edit->append("Server say:" + data);
    });

    connect(tcp_socket_, &QTcpSocket::disconnected, this, &MainWindow::DisconnectedCallback);

    connect(tcp_socket_, &QTcpSocket::stateChanged, this, [=](QAbstractSocket::SocketState socketState){
        if(socketState == QAbstractSocket::SocketState::UnconnectedState)
        {
            qDebug() << "UnconnectedState";
        }
    });
}

void MainWindow::ConnectedCallback()
{
    ui->log_text_edit->append("网络已连接");
    SwitchState(State::kConnected);
}

void MainWindow::DisconnectedCallback()
{
    ui->log_text_edit->append("连接已断开");
    SwitchState(State::kDisconnected);
}

void MainWindow::Close()
{
    tcp_socket_->close();
}

void MainWindow::SwitchState(State state)
{
    state_ = state;
    switch (state_)
    {
    case State::kDisconnected:
        status_label_->setText("未连接");

        ui->connect_btn->setEnabled(true);
        ui->disconnect_btn->setEnabled(false);
        ui->send_msg_btn->setEnabled(false);
        break;
    case State::kConnected:
        status_label_->setText("已连接");

        ui->connect_btn->setEnabled(false);
        ui->disconnect_btn->setEnabled(true);
        ui->send_msg_btn->setEnabled(true);
        break;
    }
}


void MainWindow::on_connect_btn_clicked()
{
    qDebug() << "connect_btn";
    QString ip = ui->ip_edit->text();
    ushort port = ui->port_edit->text().toUShort();
    tcp_socket_->connectToHost(QHostAddress(ip), port);
}

void MainWindow::on_send_msg_btn_clicked()
{
    qDebug() << "send_msg_btn";
    QString msg = ui->send_msg_text_edit->toPlainText();
    if(tcp_socket_->isOpen())
    {
        tcp_socket_->write(msg.toUtf8());
        ui->log_text_edit->append("Client say:" + msg);
    }
}

void MainWindow::on_disconnect_btn_clicked()
{
    qDebug() << "disconnect_btn";
    Close();
}
